package com.banhujiu.spider.region.factory

import com.banhujiu.spider.region.IOQueue
import com.banhujiu.spider.region.JSQueue
import com.banhujiu.spider.region.ProvinceQueue
import com.banhujiu.spider.region.enties.JSEntry
import com.banhujiu.spider.region.enties.RegionEntry
import com.banhujiu.spider.region.enties.RegionVo
import org.apache.logging.log4j.LogManager

/**
 * @author banhujiu
 * @date 2017/11/22 0022 14:25
 */
class Province(private val provinceQueue: ProvinceQueue, private val ioQueue: IOQueue, private val jsQueue: JSQueue) : Runnable {
    private val logger = LogManager.getLogger(this::class.java.name)

    override fun run() {
        try {
            while (!Thread.interrupted()) {
                val vo: RegionVo = provinceQueue.take()
                for (link in vo.links) {
                    val region: RegionEntry
                    try {
                        region = vo.level.buildRegion(link, vo.pRegionEntry)
                    } catch (e: Exception) {
                        logger.info(vo)
                        continue
                    }
                    ioQueue.put(region)
                    if (region.nextUrl == null) {
                        continue
                    }
                    jsQueue.put(JSEntry(region.nextUrl!!, vo.level.nextLevel()!!, region))
                }
            }
        } catch (e: InterruptedException) {
            logger.error("interrupted Province")
        }
    }
}
